package com.library.web.controller.library;

import com.alibaba.fastjson.JSON;
import com.library.common.annotation.Log;
import com.library.common.core.controller.BaseController;
import com.library.common.core.domain.AjaxResult;
import com.library.common.core.page.TableDataInfo;
import com.library.common.enums.BusinessType;
import com.library.common.utils.StringUtils;
import com.library.common.utils.poi.ExcelUtil;
import com.library.domain.BoMembers;
import com.library.service.IBoBorrowService;
import com.library.service.IBoMembersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;


/**
 * 图书管会员 信息操作处理
 *
 * @author null
 * @date 2020-01-18
 */
@RestController
@RequestMapping("/library/boMembers")
public class BoMembersController extends BaseController {
    private String prefix = "business/library/boMembers";
    private static final Logger log = LoggerFactory.getLogger(BoMembersController.class);
    @Autowired
    private IBoMembersService boMembersService;


    @Autowired
    private IBoBorrowService boBorrowService;

    /**
     * 查询图书管会员列表
     */
    @PreAuthorize("@ss.hasPermi('system:members:list')")
    @GetMapping("/list")
    public TableDataInfo list(BoMembers boMembers) {
        startPage();
        List<BoMembers> list = boMembersService.selectBoMembersList(boMembers);
        return getDataTable(list);
    }

    /**
     * 导出图书管会员列表
     */
    @PreAuthorize("@ss.hasPermi('system:members:export')")
    @Log(title = "图书管会员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BoMembers boMembers) {
        List<BoMembers> list = boMembersService.selectBoMembersList(boMembers);
        ExcelUtil<BoMembers> util = new ExcelUtil<BoMembers>(BoMembers.class);
        util.exportExcel(response, list, "图书管会员数据");
    }

    /**
     * 获取图书管会员详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:members:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(boMembersService.selectBoMembersById(id));
    }

    /**
     * 新增图书管会员
     */
    @PreAuthorize("@ss.hasPermi('system:members:add')")
    @Log(title = "图书管会员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BoMembers boMembers) {
        return toAjax(boMembersService.insertBoMembers(boMembers));
    }

    /**
     * 修改图书管会员
     */
    @PreAuthorize("@ss.hasPermi('system:members:edit')")
    @Log(title = "图书管会员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BoMembers boMembers) {
        return toAjax(boMembersService.updateBoMembers(boMembers));
    }

    /**
     * 删除图书管会员
     */
    @PreAuthorize("@ss.hasPermi('system:members:remove')")
    @Log(title = "图书管会员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("会员：");
        boolean delStatus = false;
        for (Long id : ids) {
            boolean isUse = boBorrowService.selectBorrowByMembersId(id);
            if (isUse) {
                boMembersService.deleteBoMembersByIds(id);
            } else {
                BoMembers members = boMembersService.selectBoMembersById(Long.valueOf(id));
                buffer.append(members.getMembersName());
                buffer.append(",");
                log.warn("删除会员[{}]失败,该会员存在未归还图书。", com.alibaba.fastjson.JSON.toJSONString(members));
                delStatus = true;
                continue;
            }
        }
        buffer.append("存在未归还图书，无法删除");
        if (delStatus) {
            return AjaxResult.error(buffer.toString());
        }
        return toAjax(true);
    }

    /**
     * 调整积分
     *
     * @param id   用户id
     * @param mmap 页面对象
     * @return
     */
    @GetMapping("/boIntegral/{id}")
    public String boIntegral(@PathVariable("id") Long id, ModelMap mmap) {
        BoMembers members = boMembersService.selectBoMembersById(id);
        mmap.put("boMembers", members);
        return prefix + "/boIntegral";
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(BoMembers members) {
        return boMembersService.checkLoginNameUnique(members);
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(BoMembers members) {
        return boMembersService.checkPhoneUnique(members);
    }

    /**
     * 校验用户编号
     */
    @PostMapping("/checkNoUnique")
    @ResponseBody
    public String checkNoUnique(BoMembers members) {
        return boMembersService.checkNoUnique(members);
    }

    /**
     * 根据用户编号或者手机号查询会员信息
     *
     * @param members
     * @return
     */
    @GetMapping("/searchMember")
    public AjaxResult searchMember(BoMembers members) {
        AjaxResult ajaxResult = new AjaxResult();
        String membersNo = members.getMembersNo();
        if (membersNo.length() == 11) {
            members.setMembersPhone(members.getMembersNo());
            members.setMembersNo(null);
        }
        List<BoMembers> boMembersList = boMembersService.selectBoMembersList(members);
        if (boMembersList.size() == 0) {
            return AjaxResult.error("会员信息不存在");
        } else if (boMembersList.size() > 1) {
            return AjaxResult.error("会员重复请检查");
        } else {
            return ajaxResult.put("data", boMembersList.get(0)).put("code", 200);
        }

    }

    private void formatDate(BoMembers boMembers) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            boMembers.setBirthday(format.parse(boMembers.getBirthdayFmt()));
            boMembers.setEffectiveStartTime(format.parse(boMembers.getEffectiveStartTimeFmt()));
            boMembers.setEffectiveEndTime(format.parse(boMembers.getEffectiveEndTimeFmt()));
        } catch (ParseException e) {
            try {
                log.error("会员修改失败。[{}]", JSON.toJSONString(boMembers), e);
            } catch (Exception ex) {
                log.error("json 序列化失败 ", ex);
            }
        }
    }

}
